'''
    阻塞型多进程服务器
'''

from socket import *
from multiprocessing import *
import time

def dealWithClient(newSocket, clientAddr):
    while True:
        recvData = newSocket.recv(1024)         # 阻塞
        if len(recvData):                       # recvData的len为0则表示socket关闭
            print('Client address is:', clientAddr)
            print('Recieved data is:', recvData)
        else:
            print('Client is closed')
            break
    newSocket.closed()


def main():
    serverSocket = socket(AF_INET, SOCK_STREAM)
    # tcpsocket关闭后会有个time_wait(2SML), 在这个时间内被关闭的端口号无法使用, 该设置可解除该限制
    serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    localAddr = ('', 7788)
    serverSocket.bind(localAddr)
    serverSocket.listen(5)

    try:
        while True:
            newSocket, clientAddr = serverSocket.accept()   # 阻塞
            clientProcess = Process(target=dealWithClient, args=(newSocket, clientAddr))
            clientProcess.start()
            newSocket.close()       # 进程是复制型的, 所以父进程的clientSocket可以不要了
    finally:
        serverSocket.close()

if  __name__=='__main__':
    print('Hello')
    main()